<template>
  <div class="plan-form-container">
    <!-- 页面头部 -->
    <div class="form-header">
      <h2 class="form-title">计划信息</h2>
      <div class="title-line"></div>
    </div>

    <!-- 表单内容 -->
    <div class="form-content">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        label-position="left"
        class="plan-form"
      >
        <!-- 两列布局 -->
        <div class="form-row">
          <!-- 左列 -->
          <div class="form-column">
            <el-form-item label="设备名称" prop="equipmentId" required>
              <el-select
                v-model="form.equipmentId"
                placeholder="请选择设备"
                style="width: 100%"
                filterable
                :disabled="isEdit"
              >
                <el-option
                  v-for="equipment in equipmentList"
                  :key="equipment.equipmentId"
                  :label="equipment.equipmentName"
                  :value="equipment.equipmentId"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="保养结束时间" prop="maintenanceEndTime" required>
              <el-date-picker
                v-model="form.maintenanceEndTime"
                type="date"
                placeholder="请选择时间"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                style="width: 100%"
              />
            </el-form-item>

            <el-form-item label="保养项目*" prop="maintenanceItem" required>
              <el-input
                v-model="form.maintenanceItem"
                placeholder="请输入保养项目"
                clearable
              />
            </el-form-item>
          </div>

          <!-- 右列 -->
          <div class="form-column">
            <el-form-item label="保养开始时间" prop="maintenanceStartTime" required>
              <el-date-picker
                v-model="form.maintenanceStartTime"
                type="date"
                placeholder="请选择时间"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                style="width: 100%"
              />
            </el-form-item>

            <el-form-item label="保养费用">
              <el-input
                v-model="form.maintenanceCost"
                placeholder="请输入保养费用"
                clearable
                type="number"
              />
            </el-form-item>

            <el-form-item label="负责人" prop="responsiblePerson" required>
              <el-input
                v-model="form.responsiblePerson"
                placeholder="请输入负责人"
                clearable
              />
            </el-form-item>
          </div>
        </div>

        <!-- 备注区域 -->
        <el-form-item label="备注">
          <el-input
            v-model="form.remarks"
            type="textarea"
            :rows="4"
            placeholder="请输入备注"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="form-actions">
      <el-button type="success" @click="handleSubmit" :loading="submitting">
        保存
      </el-button>
      <el-button @click="handleClose">
        取消
      </el-button>
    </div>
  </div>
</template>

<script>
import { maintenanceRecordApi, equipmentApi } from '@/api/equipment'

export default {
  name: 'MaintenanceRecordForm',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    formData: {
      type: Object,
      default: () => ({})
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:modelValue', 'success'],
  data() {
    return {
      form: {
        equipmentId: '',
        maintenanceStartTime: '',
        maintenanceEndTime: '',
        maintenanceItem: '',
        maintenanceCost: '',
        responsiblePerson: '',
        remarks: ''
      },
      rules: {
        equipmentId: [
          { required: true, message: '请选择设备', trigger: 'change' }
        ],
        maintenanceStartTime: [
          { required: true, message: '请选择保养开始时间', trigger: 'change' }
        ],
        maintenanceEndTime: [
          { required: true, message: '请选择保养结束时间', trigger: 'change' }
        ],
        maintenanceItem: [
          { required: true, message: '请输入保养项目', trigger: 'blur' }
        ],
        responsiblePerson: [
          { required: true, message: '请输入负责人', trigger: 'blur' }
        ]
      },
      equipmentList: [],
      submitting: false
    }
  },
  watch: {
    modelValue(val) {
      if (val) {
        this.initForm()
        this.loadEquipmentList()
      }
    },
    formData: {
      handler(val) {
        if (val && Object.keys(val).length > 0) {
          this.initForm()
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    // 初始化表单
    initForm() {
      if (this.isEdit && this.formData) {
        this.form = {
          equipmentId: this.formData.equipmentId || '',
          maintenanceStartTime: this.formData.maintenanceStartTime || '',
          maintenanceEndTime: this.formData.maintenanceEndTime || '',
          maintenanceItem: this.formData.maintenanceItem || '',
          maintenanceCost: this.formData.maintenanceCost || '',
          responsiblePerson: this.formData.responsiblePerson || '',
          remarks: this.formData.remarks || ''
        }
      } else {
        this.form = {
          equipmentId: '',
          maintenanceStartTime: '',
          maintenanceEndTime: '',
          maintenanceItem: '',
          maintenanceCost: '',
          responsiblePerson: '',
          remarks: ''
        }
      }
    },

    // 加载设备列表
    async loadEquipmentList() {
      try {
        const response = await equipmentApi.getEquipmentPage({
          pageNum: 1,
          pageSize: 1000 // 获取所有设备
        })
        if (response.code === 200) {
          this.equipmentList = response.data.records || []
        } else {
          this.$message.error('加载设备列表失败')
        }
      } catch (error) {
        console.error('加载设备列表失败:', error)
        this.$message.error('加载设备列表失败')
      }
    },

    // 提交表单
    async handleSubmit() {
      try {
        await this.$refs.formRef.validate()
        this.submitting = true

        const formData = { ...this.form }
        
        // 转换费用为数字类型
        if (formData.maintenanceCost) {
          formData.maintenanceCost = parseFloat(formData.maintenanceCost)
        }
        
        // 如果是编辑模式，需要添加记录ID
        if (this.isEdit) {
          formData.maintenanceRecordId = this.formData.maintenanceRecordId
        }

        const response = this.isEdit 
          ? await maintenanceRecordApi.updateMaintenanceRecord(formData)
          : await maintenanceRecordApi.addMaintenanceRecord(formData)

        if (response.code === 200) {
          this.$message.success(this.isEdit ? '修改成功' : '新增成功')
          this.$emit('success')
          this.handleClose()
        } else {
          this.$message.error(response.message || (this.isEdit ? '修改失败' : '新增失败'))
        }
      } catch (error) {
        if (error.message) {
          // 表单验证错误
          return
        }
        console.error('提交失败:', error)
        this.$message.error(this.isEdit ? '修改失败' : '新增失败')
      } finally {
        this.submitting = false
      }
    },

    // 关闭弹框
    handleClose() {
      this.$emit('update:modelValue', false)
      // 重置表单
      this.$nextTick(() => {
        if (this.$refs.formRef) {
          this.$refs.formRef.resetFields()
        }
      })
    }
  }
}
</script>

<style scoped>
.plan-form-container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding: 20px;
}

.form-header {
  background: white;
  padding: 20px 30px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.form-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin: 0 0 10px 0;
}

.title-line {
  height: 1px;
  background-color: #e0e0e0;
  width: 100%;
}

.form-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 30px;
}

.plan-form {
  max-width: 800px;
}

.form-row {
  display: flex;
  gap: 40px;
  margin-bottom: 20px;
}

.form-column {
  flex: 1;
}

.form-column .el-form-item {
  margin-bottom: 20px;
}

.form-actions {
  display: flex;
  gap: 10px;
  margin-top: 30px;
}

.form-actions .el-button {
  padding: 10px 20px;
  font-size: 14px;
}

.form-actions .el-button--success {
  background-color: #67c23a;
  border-color: #67c23a;
}

.form-actions .el-button--success:hover {
  background-color: #85ce61;
  border-color: #85ce61;
}

/* 表单项样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

:deep(.el-input__inner) {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 0 15px;
  height: 40px;
  line-height: 40px;
  font-size: 14px;
}

:deep(.el-input__inner:focus) {
  border-color: #409eff;
}

:deep(.el-textarea__inner) {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px 15px;
  font-size: 14px;
  resize: vertical;
}

:deep(.el-textarea__inner:focus) {
  border-color: #409eff;
}

:deep(.el-select .el-input__inner) {
  cursor: pointer;
}

:deep(.el-date-editor .el-input__inner) {
  cursor: pointer;
}

/* 必填项标识 */
:deep(.el-form-item.is-required .el-form-item__label::before) {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .plan-form-container {
    padding: 10px;
  }
  
  .form-header {
    padding: 15px 20px;
  }
  
  .form-content {
    padding: 20px;
  }
  
  .form-row {
    flex-direction: column;
    gap: 0;
  }
  
  .form-column {
    margin-bottom: 0;
  }
}
</style>
